/* Copyright 2009 Requirements Management System 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.model.commons.checker;

import java.sql.Connection;
import java.sql.Statement;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.validator.GenericValidator;

/**
 * 
 * @author Mario Gaitan
 *
 */
public class DerbyDataBaseChecker extends AbstractDataBaseChecker {
	public static final String DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
	public DerbyDataBaseChecker() {
		super(DRIVER_NAME);
	}
	@Override
	public Throwable createDatabase(BasicDataSource dataSource) {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(dataSource.getDriverClassName());
		ds.setUrl(dataSource.getUrl()+";create=true");
		ds.setUsername(dataSource.getUsername());
		ds.setPassword(dataSource.getPassword());
		ds.setDefaultCatalog(dataSource.getDefaultCatalog());
		Connection connection = null;
		try {
			connection = ds.getConnection();
			Statement statement = connection.createStatement();
			if(!GenericValidator.isBlankOrNull(dataSource.getUsername())) {
				statement.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.connection.requireAuthentication','true')");
				statement.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.user."+dataSource.getUsername()+"', '"+dataSource.getPassword()+"')");
			}	
			
		} catch (Exception e) {
			return (Throwable)e;
		} finally {
			try {
				if(connection!=null)
					connection.close();
			} catch(Exception e) {
				/*IGNORE EXCEPTION*/
			}
		}		
		return null;
	}
}
